<template>
  <el-dialog
    :visible.sync="visible"
    :destroy-on-close="true"
    :modal="true"
    width="720px"
    :before-close="beforeClose"
  >
    <template slot="title">
      <div class="header">
        <div class="title">添加职业</div>
        <el-input
          class="custom-input"
          size="mini"
          placeholder="输入职业关键字"
          prefix-icon="el-icon-search"
          v-model="matchName"
          @keyup.enter.native="handleSearch"
        >
        </el-input>
        <el-button
          style="margin-left: 12px"
          type="primary"
          size="mini"
          @click="handleSearch"
          >搜 索</el-button
        >
      </div>
    </template>
    <div class="container">
      <div class="left" v-show="!showSearchData">
        <el-scrollbar style="height: 100%">
          <el-menu
            :default-active="currentSecondNavId"
            :collapse="false"
            :unique-opened="true"
            ref="menuRef"
            @select="selectMenu"
            @open="fatherMenuOpen"
          >
            <el-submenu
              v-for="item in classList"
              :key="item.navId"
              :index="item.navId"
              :title="item.navName"
            >
              <template slot="title">
                <div class="titleFirst">{{ item.navName }}</div>
              </template>
              <template v-if="item.children.length > 0">
                <el-menu-item
                  v-for="temp in item.children"
                  :key="temp.navId"
                  :index="temp.navId"
                  :title="temp.navName"
                  :id="'menu' + temp.navId"
                  >{{ temp.navName }}
                </el-menu-item>
              </template>
            </el-submenu>
          </el-menu>
        </el-scrollbar>
      </div>
      <div class="right" v-loading="loading">
        <el-scrollbar style="height: 100%" v-show="!showSearchData">
          <div class="right-item" v-if="thirdListObj.navName">
            <div class="right-item-title">
              <span class="title">{{ thirdListObj.navName }}</span>
              <span class="all" @click="handleSelectAll">全部</span>
            </div>
            <div class="right-item-checkbox">
              <el-checkbox
                v-for="_item in thirdListObj.children"
                :key="_item.navId"
                :label="_item.navName"
                v-model="_item.checked"
                @change="(val) => handleChangeCheck(val, _item)"
              ></el-checkbox>
            </div>
          </div>
        </el-scrollbar>
        <el-scrollbar style="height: 100%" v-show="showSearchData">
          <div
            class="right-search"
            v-for="(item, index) in searchList"
            :key="index + 'search'"
          >
            <div class="right-search-title">
              <div class="title-box">
                <span class="first">{{ item.parentName }}</span>
                <span class="dot">•</span>
                <span> {{ item.topName }}</span>
              </div>
              <div class="all" @click="handleSelectAllSearch(item)">全部</div>
            </div>
            <div class="right-search-checkbox">
              <el-checkbox
                v-for="_item in item.children"
                :key="_item.navId"
                :label="_item.navName"
                v-model="_item.checked"
                @change="(val) => handleChangeCheck(val, _item)"
              ></el-checkbox>
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import {
  positionTreeInterface,
  searchPositionByIdInterface,
} from "@/api/home.js";
import { matchPositionList } from "@/api/mine.js";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    preSelectedList: {
      type: Array,
      default: () => [],
    },
    isSelectedAll: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.selectedList = JSON.parse(JSON.stringify(this.preSelectedList));
        this.selectedMapFormat();
        this.getClassList();
      }
    },
    matchName(val) {
      if (!val) {
        this.showSearchData = false;
        this.getThirdList();
      }
    },
  },
  data() {
    return {
      matchName: "",
      loading: false,
      currentFirstNavId: "", // 当前点击的左侧菜单一级 navId
      currentSecondNavId: "", // 当前点击的左侧菜单二级 navId
      classList: [], // 左侧数据列表
      thirdListObj: {}, // 点击左侧菜单的当前二级数据(包含三级数据)对象
      searchList: [], // 模糊搜素的数据列表
      selectedList: [], // 当前选中的列表，包括从父组件传过来的数据和当前选中的数据
      selectedMap: {}, // 当前选中的 navId 的map；
      showSearchData: false,
      listMap: {}, // 请求过的数据就不去请求了，直接在这里获取
    };
  },
  created() {},
  methods: {
    fatherMenuOpen(key) {
      let selectedFather = this.classList.filter((item) => {
        return item.navId == key;
      });
      let selectId = selectedFather[0].children[0].navId;
      this.selectMenu(selectId, [key, selectId]);
    },
    selectMenu(index, indexPath) {
      this.currentFirstNavId = indexPath[0];
      this.currentSecondNavId = index;
      // 如果在map中已经存在数据，就在map中获取数据，不去请求
      if (this.listMap[this.currentFirstNavId]) {
        this.thirdListObj = this.listMap[this.currentFirstNavId].find(
          (item) => item.navId == this.currentSecondNavId
        );
        return;
      }
      this.getThirdList();
    },

    handleChangeCheck(val, item) {
      if (val) {
        // 每次选中，添加进去选中列表和map中
        if (!this.selectedMap[item.navId]) {
          this.selectedMap[item.navId] = {
            checked: true, // checked是当前弹框中选中职业的标识
            isSelected: false, // 这个字段是多选时候选中的标识，是父组件用到的字段
          };
          this.selectedList.push(item);
        }
      } else {
        // 每次反选，就从选中列表和map中清除
        delete this.selectedMap[item.navId];
        const index = this.selectedList.findIndex(
          (_item) => _item.navId === item.navId
        );
        this.selectedList.splice(index, 1);
      }
      this.$emit("confirm", this.selectedList);
    },
    selectedMapFormat() {
      const map = {};
      this.preSelectedList.forEach((item) => {
        map[item.navId] = {
          checked: true,
          isSelected: item.isSelected,
        };
      });
      this.selectedMap = map;
    },
    handleSelectAll() {
      this.thirdListObj.allChecked = !this.thirdListObj.allChecked;
      if (this.thirdListObj.children && this.thirdListObj.children.length) {
        if (this.thirdListObj.allChecked) {
          // 如果当前全部选中，把checked为false的项置为true，并添加到列表和map中
          this.thirdListObj.children.forEach((val) => {
            if (!val.checked) {
              this.$set(val, "checked", true);
              this.selectedList.push(val);
              this.selectedMap[val.navId] = {
                checked: true,
                isSelected: false,
              };
            }
          });
          this.$emit("confirm", this.selectedList);
        } else {
          // 当前全部不选中，把子项全部变成false，并从列表和map中删除
          this.thirdListObj.children.forEach((val) => {
            this.$set(val, "checked", false);
            const index = this.selectedList.findIndex(
              (_item) => _item.navId == val.navId
            );
            this.selectedList.splice(index, 1);
            delete this.selectedMap[val.navId];
          });
          this.$emit("confirm", this.selectedList);
        }
      }
    },
    handleSelectAllSearch(item) {
      item.allChecked = !item.allChecked;
      if (item.children && item.children.length) {
        if (item.allChecked) {
          // 如果当前全部选中，把checked为false的项置为true，并添加到列表和map中
          item.children.forEach((val) => {
            if (!val.checked) {
              this.$set(val, "checked", true);
              this.selectedList.push(val);
              this.selectedMap[val.navId] = {
                checked: true,
                isSelected: false,
              };
            }
          });
          this.$emit("confirm", this.selectedList);
        } else {
          // 当前全部不选中，把子项全部变成false，并从列表和map中删除
          item.children.forEach((val) => {
            this.$set(val, "checked", false);
            const index = this.selectedList.findIndex(
              (_item) => _item.navId == val.navId
            );
            this.selectedList.splice(index, 1);
            delete this.selectedMap[val.navId];
          });
          this.$emit("confirm", this.selectedList);
        }
      }
    },
    clearAll() {
      this.listMap = {};
      this.selectedMap = {};
      this.thirdListObj = {};
    },
    handleSearch() {
      if (!this.matchName) return;
      this.searchList = [];
      this.showSearchData = true;
      this.loading = true;
      const params = {
        matchName: this.matchName,
        pageNo: 1,
        pageSize: 200,
      };
      matchPositionList(params)
        .then((res) => {
          if (res.code == 200) {
            this.arrayToTree(res.data);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 数组变成树
    arrayToTree(arr) {
      const tempList = [];
      const map = {};
      for (let i = 0; i < arr.length; i++) {
        if (map[arr[i].parentId]) {
          const temp = tempList.find((item) => item.navId === arr[i].parentId);
          if (temp) {
            temp.children.push({
              navName: arr[i].positionName,
              navId: arr[i].navId,
              valueId: arr[i].ylPositionId,
              parentId: arr[i].parentId,
              checked: false,
            });
          }
        } else {
          map[arr[i].parentId] = true;
          const {
            parentId,
            topName,
            parentName,
            navId,
            positionName,
            ylPositionId,
          } = arr[i];
          tempList.push({
            topName: topName,
            parentName: parentName,
            navId: parentId,
            allChecked: false,
            children: [
              {
                navName: positionName,
                navId: navId,
                valueId: ylPositionId,
                parentId: parentId,
                checked: false,
              },
            ],
          });
        }
      }
      // 根据当前已经选中的map修改搜索列表的checked状态
      tempList.forEach((item) => {
        if (item.children && item.children.length) {
          let count = 0;
          item.children.forEach((_item) => {
            if (this.selectedMap[_item.navId]) {
              this.$set(_item, "checked", true);
              count++;
            }
          });
          if (count == item.children.length) {
            this.$set(item, "allChecked", true);
          }
        }
      });
      this.searchList = tempList;
    },
    handleClose() {
      this.matchName = "";
      this.currentFirstNavId = "";
      this.selectedMap = {};
      this.thirdListObj = {};
      this.classList = [];
      this.$emit("update:visible", false);
    },
    beforeClose() {
      this.handleClose();
    },
    getClassList() {
      positionTreeInterface({
        careerTagIds: "",
      }).then((res) => {
        if (res.code == 200 && Array.isArray(res.data)) {
          res.data.forEach((item) => {
            this.$set(item, "checked", false);
          });
          this.classList = res.data;
          this.currentFirstNavId = this.classList[0].navId;
          this.currentSecondNavId = this.classList[0].children[0].navId;
          this.selectMenu(this.currentSecondNavId, [
            this.currentFirstNavId,
            this.currentSecondNavId,
          ]);
        }
      });
    },
    getThirdList() {
      this.loading = true;
      searchPositionByIdInterface({
        navIds: this.currentFirstNavId,
      })
        .then((res) => {
          if (res.code == 200) {
            res.data[0].children.forEach((item) => {
              item.allChecked = false;
              if (item.children && item.children.length) {
                item.children.forEach((_item) => {
                  this.$set(_item, "checked", false);
                });
              }
            });
            this.listMap[this.currentFirstNavId] = res.data[0].children;
            res.data[0].children.forEach((item) => {
              let checkedCount = 0; // checked = true 的子元素个数和总子元素个数相等那么 allChecked = true;
              if (item.children && item.children.length) {
                item.children.forEach((_item) => {
                  this.$set(_item, "isSelected", false); // 添加选中下载时候的标识
                  if (this.selectedMap[_item.navId]?.checked) {
                    this.$set(_item, "checked", true); // 显：checked:选中当前职业的标识
                    checkedCount++;
                  } else {
                    this.$set(_item, "checked", false);
                  }
                });
                if (item.children.length === checkedCount) {
                  this.$set(item, "allChecked", true);
                } else {
                  this.$set(item, "allChecked", false);
                }
              }
            });
            this.thirdListObj = res.data[0].children[0];
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style scoped lang="scss">
$main-color: #0b6eff;
.header {
  display: flex;
  align-items: center;
  border-bottom: 1px solid #c8d4e6;
  padding-bottom: 12px;
  .title {
    font-size: 18px;
    color: #222;
    margin: 4px 14px 0 16px;
  }
  .custom-input {
    width: 313px;
    ::v-deep .el-input__inner {
      background: #e8e8e8;
    }
  }
}
.container {
  height: 480px;
  display: flex;
  font-size: 14px;
  .left {
    padding: 8px 0;
    height: 100%;
    width: 176px;
    flex-shrink: 0;
    border-right: 1px solid #c8d4e6;
    ::v-deep .el-submenu__title {
      height: 36px;
      line-height: 36px;
      font-size: 14px;
    }
    ::v-deep .el-menu-item {
      height: 36px;
      line-height: 36px;
      padding-left: 34px !important;
    }
  }
  .all {
    width: 50px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border: 1px solid #9ea9c1;
    border-radius: 3px;
    margin-left: 12px;
    cursor: pointer;
    user-select: none;
    font-size: 13px;
  }
  .right {
    flex: 1;
    padding: 8px 0 12px 18px;
    &-item {
      color: #555;
      &-title {
        display: flex;
        align-items: center;
        padding: 4px 0 15px 0;
        &::before {
          content: " ";
          width: 3px;
          height: 13px;
          background-color: $main-color;
          border-radius: 2px;
          transform: translateY(1px);
        }
        .title {
          font-size: 16px;
          padding-left: 8px;
          padding-top: 3px;
          font-weight: 600;
        }
        .active {
          background: $main-color;
          color: #fff;
          border-color: $main-color;
        }
      }
      &-checkbox {
        margin-bottom: 6px;
      }
    }
    &-search {
      &-title {
        display: flex;
        align-items: center;
        padding: 4px 0 12px 0;
        .title-box {
          color: #999;
          display: flex;
          align-items: center;
          font-size: 13px;
          display: flex;
          align-items: center;
          padding-top: 4px;
          .dot {
            padding: 0 4px;
            font-size: 12px;
            padding-top: 1px;
          }
          .active {
            background: $main-color;
            color: #fff;
            border-color: $main-color;
          }
        }
      }
    }
  }
}
::v-deep .el-button--primary {
  color: #fff;
  background-color: $main-color;
  border-color: $main-color;
}
::v-deep .el-button--primary:focus,
.el-button--primary:hover {
  color: #fff;
  background-color: $main-color;
  border-color: $main-color;
}
::v-deep .el-input__inner:focus {
  border-color: $main-color;
}
::v-deep .el-input__inner::placeholder {
  color: #a5a5a5;
}
::v-deep .el-dialog__headerbtn {
  top: 16px;
  right: 16px;
}
::v-deep .el-icon-close:before {
  font-size: 22px;
  color: #000;
}
::v-deep .el-icon-search:before {
  color: #222;
}
::v-deep .el-dialog__wrapper {
  z-index: 999999 !important; // 因为会被预览文档的层级挡住弹框的点击
}
::v-deep .el-dialog {
  border-radius: 8px;
}
::v-deep .el-dialog__header {
  padding: 12px 0 0 0;
}
::v-deep .el-dialog__body {
  padding: 0;
}

::v-deep .el-checkbox {
  margin: 0 40px 16px 0;
  .el-checkbox__inner {
    border-radius: 3px;
    background: transparent;
    border-color: #9c9c9c;
  }
  .el-checkbox__input.is-checked .el-checkbox__inner {
    border-color: $main-color;
  }
  .el-checkbox__inner::after {
    border: 1px solid $main-color;
    border-left: 0;
    border-top: 0;
  }
}
</style>
